import User from '../model/user.model'
const {
  handleRequest,
  handleError,
  handleSuccess
  // handleThrottle
} = require('../utils/handle')

const jwt = require('jsonwebtoken')
const crypto = require('crypto')

const authCtrl = { login: {}, user: {}, register: {} }

// md5 编码
const md5Decode = pwd => {
  return crypto
    .createHash('md5')
    .update(pwd)
    .digest('hex')
}
authCtrl.user.GET = async ctx => {
  console.log(ctx.query)
  handleSuccess({
    ctx,
    result: ctx.query,
    message: '获取用户资料成功'
  })
}
// 登录
authCtrl.login.POST = async ctx => {
  const { username, passwd } = ctx.request.body
  const auth = await User.findOne({ username }).catch(() => ctx.throw(500, '服务器内部错误'))
  if (auth) {
    if (auth.passwd === md5Decode(passwd)) {
      const token = jwt.sign({
        name: auth.username,
        password: auth.passwd,
        exp: Math.floor(Date.now() / 1000) + 60 * 60
      }, 'my_blog')
      handleSuccess({
        ctx,
        result: {
          token,
          lifeTime: Math.floor(Date.now() / 1000) + 60 * 60
        },
        message: '登陆成功'
      })
    } else {
      handleError({ ctx, message: '密码错误!' })
    }
  } else {
    handleError({ ctx, message: '账户不存在' })
  }
}

authCtrl.register.POST = async ctx => {
  const { userName, passwd } = ctx.request.body
  // 此处可以做一下验证
  // 查数据库 看是否已存在
  const auth = await User.findOne({userName}).catch((err) => {
    ctx.throw(500, '服务器内部错误', err)
  })
  if (!auth) {
    let userModel = new User({
      userName,
      passwd: md5Decode(passwd)
    })
    // 用户保存
    const res = userModel.save().catch(() => {
      ctx.throw(500, '服务器内部错误')
    })
    if (res) {
      handleSuccess({
        ctx,
        result: res,
        message: '注册成功'
      })
    } else {
      handleError({
        ctx,
        message: '注册失败'
      })
    }
  } else {
    handleError({
      ctx,
      message: '账户已存在'
    })
  }
}
export default {
  login: ctx => handleRequest({ctx, controller: authCtrl.login}),
  register: ctx => handleRequest({ctx, controller: authCtrl.register}),
  user: ctx => handleRequest({ctx, controller: authCtrl.user})
}
